//
//  VoteMasterDetailViewController.m
//  homeland
//
//  Created by gzbugu on 14-7-31.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//  民意征集／我要投票详情展示类
//

#import "VoteMasterDetailViewController.h"
#import "UIImageView+WebCache.h"
#import "VoteMasterEntity.h"
#import "UserInfoService.h"
#import "CheckButton.h"
#import "RadioGroup.h"
#import <QuartzCore/QuartzCore.h>

#import "XHImageViewer.h"
#import "UIImageView+XHURLDownload.h"
#import "VoteItemDetailViewController.h"

#define INPUT_VIEW_OFFSET 200.0

//扩展属性
@interface VoteMasterDetailViewController() <XHImageViewerDelegate> {
    //当前页面－图片集
    NSMutableArray *_imageViews;
    //手势识别事件
    UITapGestureRecognizer *_gesture;
}
//变量区
//=========================
//定义一个变量来记录下一个将要添加的控件的位置
@property (assign, nonatomic) int nextY;
//调查主体id
@property (strong, nonatomic) NSString *masterId;
//获取的调查项结果集
@property (strong, nonatomic) NSDictionary *jsonData;
//投票总数
@property (assign, nonatomic) NSInteger voteItemSum;
//是否投过票，大于零表示投过
@property (assign, nonatomic) NSInteger countNum;
//是否结束，等于零表示过期
@property (assign, nonatomic) NSInteger isEnd;
//是否复选（多选）
@property (assign, nonatomic) NSInteger isMulti;
//投票项展示类型: 0列表,1图片,2列表+意见,3图片+意见
@property (assign, nonatomic) NSInteger showType;
//投票统计结果是否展示：0为不展示 1为展示
@property (assign, nonatomic) NSInteger resultShowType;
//社区自治类型 1.社区民意征集2.社区我要投票
@property (assign, nonatomic) NSInteger communityCategory;
//意见项
@property (strong, nonatomic) NSDictionary *opinionData;
//意见内容框
@property (strong, nonatomic) UITextView *opinionField;
//存储单选投票结果：key是题目id,value是选中的条目id
@property (strong, nonatomic) NSMutableDictionary *rResultDic;
//存储复选投票结果：key是题目id,value是选中的条目id集（一个或多个）
@property (strong, nonatomic) NSMutableDictionary *cResultDic;

//意见提交按扭
@property (strong, nonatomic) UIButton *opinionBtn;
//提交按扭
@property (strong, nonatomic) UIButton *postBtn;
@end

@implementation VoteMasterDetailViewController
//唯一静态变量key－用于关联函数传参
static const char associatedkey;
//方法区
//=========================
-( id )initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self =[ super initWithNibName :nibNameOrNil bundle :nibBundleOrNil];
    if (self){
        
    }
    return self ;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"详情";
    
    [self configView];
}

/**数据渲染展示*/
-(void)configView{
    //初始化参数
    _nextY = 0;
    _rResultDic = [NSMutableDictionary dictionary];
    _cResultDic = [NSMutableDictionary dictionary];
    _imageViews = [NSMutableArray array];
    //主体内容展示
    //--------------------------
    VoteMasterEntity *item = [_config objectForKey:@"dataItem"];
    //主体id
    _masterId = [CommonUtil dealNullObject:item.Id];
    //是否投过票，大于零表示投过
    
    _countNum = [CommonUtil dealNullObject:item.countNum].intValue;
    
    //是否结束，等于零表示过期
    _isEnd = (NSNull *)item.isEnd == [NSNull null] ?1:[CommonUtil dealNullObject:item.isEnd].intValue;
    //是否多选
    _isMulti = [CommonUtil dealNullObject:item.isMulti].intValue;
    //投票项展示类型: 0列表,1图片,2列表+意见,3图片+意见
    _showType =[CommonUtil dealNullObject:item.voteShowType].intValue;
    //投票统计结果是否展示：0为不展示 1为展示
    _resultShowType =[CommonUtil dealNullObject:item.voteResultShowType].intValue;
    //社区自治类型 1.社区民意征集2.社区我要投票
    _communityCategory = [CommonUtil dealNullObject:item.communityCategory].intValue;
    //展示图片
    //--------------------
    NSString *pic = [NSString stringWithFormat:@"http://%@%@", SERVER_URL_COMMUNITY_VOTE_IMAGE, item.voteImage];
    //初始化
    [self initImageView:self.imageView  setImageUrl:pic setParam:@"" setIsBusi:NO];
    
    //展示主体内容
    //-------------------
    NSString *_Vtitle = [CommonUtil dealNullObject:item.voteTitle];
    NSString *_Vcontent = [CommonUtil dealNullObject:item.voteContext];
    //根据内容调整高度
    CGFloat titleHeight = [self caculateHeightForString:_Vtitle AndFontSize:16.0f AndWitdh:300.0f];
    CGFloat contentHeight = [self caculateHeightForString:_Vcontent AndFontSize:14.0f AndWitdh:300.0f];
    
    self.titleTextView.frame = CGRectMake(0.0,10.0, 300.0, titleHeight);
    self.titleTextView.text = _Vtitle;
    
    //间隔线
    self.spiritLine.frame = CGRectMake(10.0, CGRectGetMaxY(self.titleTextView.frame), 280.0, 0.5);
    
    self.contentTextView.frame = CGRectMake(0.0, CGRectGetMaxY(self.spiritLine.frame), 300.0, contentHeight);
    self.contentTextView.text = _Vcontent;
    self.contentTextView.font = [UIFont systemFontOfSize:14.0f];
    
    self.timePanel.frame = CGRectMake(0.0, CGRectGetMaxY(self.contentTextView.frame) + 5.0, 300.0, 21.0);
    self.startDateLabel.text = [CommonUtil formatDateStr:item.startTime style:@"yyyy-MM-dd"];
    self.endDateLabel.text = [CommonUtil formatDateStr:item.endTime style:@"yyyy-MM-dd"];
    
    //设置内容区域高度及边框：
    self.contentPanel.frame = CGRectMake(10.0, CGRectGetMaxY(self.imageView.frame) + 10.0, 300.0, titleHeight + contentHeight + 40.5);
    //TODO——待处理边框范围问题
    //self.contentPanel.layer.borderColor = UIColor.grayColor.CGColor;
    //self.contentPanel.layer.borderWidth =1.0;
    
    _nextY+= (CGRectGetMaxY(self.contentPanel.frame) + 10.0);//下一元素显示的位置
    NSLog(@"下一元素的位置为：%d",_nextY);
    //投票项／意见项内容展示
    //--------------------------
    [self getItemContent:item.Id];
}

//投票项展示相关方法
//========================

/**获取投票项／意见项数据并展示*/
- (void)getItemContent:(NSString *)surveyId{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    if ([params objectForKey:@"userId"]==nil) {
        [params setValue:userInfo.userInfo.Id forKey:@"userID"];
    }
    //请求链接
    NSString *getDataUrl = @"";
    if(_countNum > 0){//已投过票
        getDataUrl = [NSString stringWithFormat:@"%@/%@", SERVER_URL_VOTE_DETAIL_LIST, surveyId];
    }else{//未投过票的
        getDataUrl = [NSString stringWithFormat:@"%@/%@", SERVER_URL_VOTE_ITEM_LIST, surveyId];
    }
    
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:getDataUrl customHeaderFields:nil];
    //请求服务端数据
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        _jsonData = [completedOperation responseJSON];
        //投票总数
        _voteItemSum = [CommonUtil dealNullObject:[_jsonData objectForKey:@"voteItemSum"]].intValue;
        //处理数据展示
        _jsonData = [_jsonData objectForKey:@"voteItemList"];
        if (_showType==1 || _showType==3) {//图片版
            [self createImageItemZone:_jsonData];
        }else{//文字版
            [self createTextItemZone:_jsonData];
        }
        
        if(_countNum > 0){//已投过票
            if (_resultShowType == 1 && _voteItemSum>0) {//显示投票结果
                //投票结果
                [self createVoteResult:_jsonData];
                //展示意见项
                if (_communityCategory == 1 &&(_showType==2 || _showType==3)) {//民意征集中，含有意见项的
                    NSString *opinion =[CommonUtil dealNullObject:[_opinionData objectForKey:@"voteOpinion"]];//意见内容
                    //展示意见内容
                    [self createOpinionZone];
                    //判断是否有内容，若无则表示还没发表意见，若有则表示已发表意见
                    if ([opinion equals:@""]) {
                        //创建意见提交按钮
                        _opinionBtn = [self createOpinionBtn];
                    }
                }
            }
        }else{//未投过票的则显示提交按钮
            //未投过票且已过期
            if(_isEnd==0){
                [self createBtn:@"end"];
            }else{
                _postBtn = [self createBtn:@"post"];
            }
        }
        
        CGFloat totalHeight = MAX(_nextY+50, CGRectGetHeight(self.scrollView.frame));
        self.mainPanel.frame = CGRectMake(0.0, 0.0, 320.0, totalHeight);
        [self.scrollView addSubview:self.mainPanel];
        self.scrollView.contentSize = self.mainPanel.frame.size;
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        
    }];
    [currentEngine enqueueOperation:op];
}

/**创建投票项展示区域－文字＋单选或多选
 *@param json 数据内容
 **/
- (void)createTextItemZone:(NSDictionary *)json{
    //分割线-没有解决边框显示问题,暂时这样处理
    UITextView* spiritLine = [[UITextView alloc] initWithFrame:CGRectMake(10, _nextY, 300, 0.5)];
    spiritLine.backgroundColor = [UIColor blackColor];
    [self.mainPanel addSubview:spiritLine];
    
    _nextY += 10.5;//与下一元素的垂直间距为10.5
    
    int itemNum=1;
    int detailsType = -1;//0表示列表投票项，1表示图片投票项，2表示意见项
    if (_isMulti==0) {//0表示多选模式
        for(NSDictionary *nsd in json){
            detailsType = [CommonUtil dealNullObject:[nsd objectForKey:@"detailsType"]].intValue;
            if (detailsType == 0) {
                //选项
                //--------------
                // 第 i 个复选按钮
                CheckButton * cb=[[ CheckButton alloc ] initWithFrame : CGRectMake (20, _nextY , 32 , 32 )];
                //处理选中状态及可用状态
                NSInteger isCheck = [CommonUtil dealNullObject:[nsd objectForKey:@"voteResultID"]].intValue;
                //初始化
                [self initCheckButton:cb labelStr:@"" setValue:[CommonUtil dealNullObject:[nsd objectForKey:@"id"]] setCheck:isCheck];
                // 加入视图
                [self.mainPanel addSubview :cb];
                
                //选项内容－文字（左右布局）
                //--------------
                NSString * labelStr = [CommonUtil dealNullObject:[nsd objectForKey:@"voteItemContext"]];
                UIButton *labelBtn = [[UIButton alloc] initWithFrame:CGRectMake(52, _nextY, 250, 32)];
                [labelBtn setTitle:labelStr forState:UIControlStateNormal];
                labelBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
                [labelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                labelBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;//文字水平居左
                labelBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter ;//文字垂直居中
                //使文字距离左边框保持10个像素的距离。
                labelBtn.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
                if (_communityCategory == 2){//我要投票
                    //添加事件
                    //使用关联函数方式传递参数－扩展属性
                    objc_setAssociatedObject(labelBtn, &associatedkey, [CommonUtil dicToString:nsd], OBJC_ASSOCIATION_RETAIN);
                    [labelBtn addTarget:self action:@selector(viewTextItemDetail:) forControlEvents:64];
                }
                [self.mainPanel addSubview:labelBtn];
                
                _nextY += 42;//与下一元素的垂直间距为42
                itemNum++;
            }else if(detailsType == 2){//意见项
                _opinionData = nsd;
            }
        }
    }else{//1表示单选模式
        // 单选按钮组
        RadioGroup *rg =[[ RadioGroup alloc ] init ];
        for(NSDictionary *nsd in json){
            detailsType = [CommonUtil dealNullObject:[nsd objectForKey:@"detailsType"]].intValue;
            if (detailsType == 0){
                // 第 i 个单选按钮
                CheckButton * cb=[[ CheckButton alloc ] initWithFrame : CGRectMake (20, _nextY, 32, 32)];
                //处理选中状态及可用状态
                NSInteger isCheck = [CommonUtil dealNullObject:[nsd objectForKey:@"voteResultID"]].intValue;
                //初始化
                [self initRadioButton:cb labelStr:@"" setValue:[CommonUtil dealNullObject:[nsd objectForKey:@"id"]] setCheck:isCheck];
                // 加入视图
                [self.mainPanel addSubview :cb];
                // 把单选按钮加入按钮组
                [ rg add :cb];
                
                //选项内容－文字（左右布局）
                //--------------
                NSString * labelStr = [CommonUtil dealNullObject:[nsd objectForKey:@"voteItemContext"]];
                UIButton *labelBtn = [[UIButton alloc] initWithFrame:CGRectMake(52, _nextY, 250, 32)];
                [labelBtn setTitle:labelStr forState:UIControlStateNormal];
                labelBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
                [labelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                labelBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;//文字水平居左
                labelBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter ;//文字垂直居中
                //使文字距离左边框保持10个像素的距离。
                labelBtn.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
                if (_communityCategory == 2){//我要投票
                    //添加事件
                    //使用关联函数方式传递参数－扩展属性
                    objc_setAssociatedObject(labelBtn, &associatedkey, [CommonUtil dicToString:nsd], OBJC_ASSOCIATION_RETAIN);
                    [labelBtn addTarget:self action:@selector(viewTextItemDetail:) forControlEvents:64];
                }
                [self.mainPanel addSubview:labelBtn];
                
                _nextY += 42;//与下一元素的垂直间距为42
                itemNum++;
            }else if(detailsType == 2){//意见项
                _opinionData = nsd;
            }
        }
    }
}

/**创建投票项展示区域－图片＋单选或多选
 *@param json 数据内容
 **/
- (void)createImageItemZone:(NSDictionary *)json{
    //分割线-没有解决边框显示问题,暂时这样处理
    UITextView* spiritLine = [[UITextView alloc] initWithFrame:CGRectMake(10, _nextY, 300, 0.5)];
    spiritLine.backgroundColor = [UIColor blackColor];
    [self.mainPanel addSubview:spiritLine];
    
    _nextY += 10.5;//与下一元素的垂直间距为10.5
    
    int itemNum=1;
    int nextXY = 0;//第二列的y坐标点
    int detailsType = -1;//0表示列表投票项，1表示图片投票项，2表示意见项
    if (_isMulti==0) {//0表示复选模式
        for(NSDictionary *nsd in json){
            detailsType = [CommonUtil dealNullObject:[nsd objectForKey:@"detailsType"]].intValue;
            if (detailsType == 1) {
                if (itemNum%2>0) {//奇数列
                    //图片展示
                    UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(20, _nextY, 100,110)];
                    NSString *imageUrl = [NSString stringWithFormat:@"http://%@%@", SERVER_URL_COMMUNITY_VOTE_IMAGE, [CommonUtil dealNullObject:[nsd objectForKey:@"voteItemImg"]]];
                    //初始化
                    [self initImageView:imageView  setImageUrl:imageUrl setParam:[CommonUtil dicToString:nsd] setIsBusi:YES];
                    // 加入视图
                    [self.mainPanel addSubview :imageView];
                    
                    // 第 i 个复选按钮
                    CheckButton * cb=[[ CheckButton alloc ] initWithFrame : CGRectMake (20, _nextY+120, 125, 32)];
                    NSString * labelStr = [CommonUtil dealNullObject:[nsd objectForKey:@"voteItemContext"]];
                    //处理选中状态及可用状态
                    NSInteger isCheck = [CommonUtil dealNullObject:[nsd objectForKey:@"voteResultID"]].intValue;
                    //初始化
                    [self initCheckButton:cb labelStr:labelStr setValue:[CommonUtil dealNullObject:[nsd objectForKey:@"id"]] setCheck:isCheck];
                    // 加入视图
                    [self.mainPanel addSubview :cb];
                    
                    nextXY = _nextY;//并排元素
                    _nextY += 162;//与下一元素的垂直间距为162
                }else{//若为偶数行的就并排放
                    //图片展示
                    UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(170, nextXY, 100,110)];
                    NSString *imageUrl = [NSString stringWithFormat:@"http://%@%@", SERVER_URL_COMMUNITY_VOTE_IMAGE, [CommonUtil dealNullObject:[nsd objectForKey:@"voteItemImg"]]];
                    //初始化
                    [self initImageView:imageView  setImageUrl:imageUrl setParam:[CommonUtil dicToString:nsd] setIsBusi:YES];
                    // 加入视图
                    [self.mainPanel addSubview :imageView];
                    
                    // 第 i 个复选按钮
                    CheckButton * cb=[[ CheckButton alloc ] initWithFrame : CGRectMake (170, nextXY+120, 125, 32)];
                    
                    NSString * labelStr = [CommonUtil dealNullObject:[nsd objectForKey:@"voteItemContext"]];
                    //处理选中状态及可用状态
                    NSInteger isCheck = [CommonUtil dealNullObject:[nsd objectForKey:@"voteResultID"]].intValue;
                    //初始化
                    [self initCheckButton:cb labelStr:labelStr setValue:[CommonUtil dealNullObject:[nsd objectForKey:@"id"]] setCheck:isCheck];
                    // 加入视图
                    [self.mainPanel addSubview :cb];
                }
                itemNum++;
            }else if(detailsType == 2){//意见项
                _opinionData = nsd;
            }
        }
    }else{//1表示单选模式
        // 单选按钮组
        RadioGroup *rg =[[ RadioGroup alloc ] init ];
        for(NSDictionary *nsd in json){
            detailsType = [CommonUtil dealNullObject:[nsd objectForKey:@"detailsType"]].intValue;
            if (detailsType == 1) {
                if (itemNum%2>0) {//奇数列
                    //图片展示
                    UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(20, _nextY, 100,110)];
                    NSString *imageUrl = [NSString stringWithFormat:@"http://%@%@", SERVER_URL_COMMUNITY_VOTE_IMAGE, [CommonUtil dealNullObject:[nsd objectForKey:@"voteItemImg"]]];
                    //初始化
                    [self initImageView:imageView  setImageUrl:imageUrl setParam:[CommonUtil dicToString:nsd] setIsBusi:YES];
                    // 加入视图
                    [self.mainPanel addSubview :imageView];
                    
                    // 第 i 个单选按钮
                    CheckButton * cb=[[ CheckButton alloc ] initWithFrame : CGRectMake (20, _nextY+120, 125, 32)];
                    NSString * labelStr = [CommonUtil dealNullObject:[nsd objectForKey:@"voteItemContext"]];
                    //处理选中状态及可用状态
                    NSInteger isCheck = [CommonUtil dealNullObject:[nsd objectForKey:@"voteResultID"]].intValue;
                    //初始化
                    [self initRadioButton:cb labelStr:labelStr setValue:[CommonUtil dealNullObject:[nsd objectForKey:@"id"]] setCheck:isCheck];
                    // 加入视图
                    [self.mainPanel addSubview :cb];
                    // 把单选按钮加入按钮组
                    [ rg add :cb];
                    
                    nextXY = _nextY;//并排元素
                    _nextY += 162;//与下一元素的垂直间距为162
                }else{//若为偶数行的就并排放
                    //图片展示
                    UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(170, nextXY, 100,110)];
                     NSString *imageUrl = [NSString stringWithFormat:@"http://%@%@", SERVER_URL_COMMUNITY_VOTE_IMAGE, [CommonUtil dealNullObject:[nsd objectForKey:@"voteItemImg"]]];
                    //初始化
                    [self initImageView:imageView  setImageUrl:imageUrl setParam:[CommonUtil dicToString:nsd] setIsBusi:YES];
                    // 加入视图
                    [self.mainPanel addSubview :imageView];
                    
                    // 第 i 个单选按钮
                    CheckButton * cb=[[ CheckButton alloc ] initWithFrame : CGRectMake (170, nextXY+120, 125, 32)];
                    NSString * labelStr = [CommonUtil dealNullObject:[nsd objectForKey:@"voteItemContext"]];
                    //处理选中状态及可用状态
                    NSInteger isCheck = [CommonUtil dealNullObject:[nsd objectForKey:@"voteResultID"]].intValue;
                    //初始化
                    [self initRadioButton:cb labelStr:labelStr setValue:[CommonUtil dealNullObject:[nsd objectForKey:@"id"]] setCheck:isCheck];
                    // 加入视图
                    [self.mainPanel addSubview :cb];
                    // 把单选按钮加入按钮组
                    [ rg add :cb];
                }
                itemNum++;
            }else if(detailsType == 2){//意见项
                _opinionData = nsd;
            }
        }
    }
}

//初始化单选框
-(void)initRadioButton:(CheckButton*)cb  labelStr:(NSString*)labelStr setValue:(NSString*)value setCheck:(NSInteger)isCheck{
    CGSize labelSize = [labelStr sizeWithFont:[UIFont systemFontOfSize:13]
                            constrainedToSize:CGSizeMake(300.0, 100)
                                lineBreakMode:NSLineBreakByWordWrapping];
    cb.label.font = [UIFont systemFontOfSize:13];//字体大小
    cb.label.textAlignment = NSTextAlignmentLeft;//文字居左显示
    cb.label.numberOfLines = 0;//表示label可以多行显示
    cb.label.lineBreakMode = NSLineBreakByWordWrapping;//换行模式，与上面的计算保持一致。
    cb.label.frame = CGRectMake(cb.label.frame.origin.x, cb.label.frame.origin.y, cb.label.frame.size.width, labelSize.height);//保持原来Label的位置和宽度，只是改变高度。
    cb.label.text = labelStr;
    cb.label.textColor = [UIColor orangeColor];
    cb.style = CheckButtonStyleRadio ;
    cb. value = value;
    [cb addTarget:self action:@selector(radioClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    if(isCheck > 0){//已选中
        cb.checked = YES;
    }
    if(_countNum > 0||_isEnd==0){//已投过票或已结束
        cb.enabled = NO;
    }
    
}

//初始化复选框
-(void)initCheckButton:(CheckButton*)cb  labelStr:(NSString*)labelStr setValue:(NSString*)value setCheck:(NSInteger)isCheck{
    CGSize labelSize = [labelStr sizeWithFont:[UIFont systemFontOfSize:13]
                            constrainedToSize:CGSizeMake(300.0, 100)
                                lineBreakMode:NSLineBreakByWordWrapping];
    cb.label.font = [UIFont systemFontOfSize:13];//字体大小
    cb.label.textAlignment = NSTextAlignmentLeft;//文字居左显示
    cb.label.numberOfLines = 0;//表示label可以多行显示
    cb.label.lineBreakMode = NSLineBreakByWordWrapping;//换行模式，与上面的计算保持一致。
    cb.label.frame = CGRectMake(cb.label.frame.origin.x, cb.label.frame.origin.y, cb.label.frame.size.width, labelSize.height);//保持原来Label的位置和宽度，只是改变高度。
    cb.label.text = labelStr;
    cb.label.textColor = [UIColor orangeColor];
    cb.style = CheckButtonStyleBox;
    cb. value = value;
    [cb addTarget:self action:@selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    if(isCheck > 0){//已选中
        cb.checked = YES;
    }
    if(_countNum > 0||_isEnd==0){//已投过票或已结束
        cb.enabled = NO;
    }
}

/**
 *初始化图片展示
 *
 *@param imageView 图片容器
 *@param imageUrl 图片远程url
 *@param param 需要传递的参数
 *@param isBusi 是否选项图片yes是，no否
 */
-(void)initImageView:(UIImageView *) imageView  setImageUrl:(NSString*)imageUrl setParam:(NSString*)param setIsBusi:(BOOL) isBusi{
    __block UIActivityIndicatorView *activityIndicator;
    __weak UIImageView *weakImageView = imageView;
    [imageView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"placeholder.png"] options:SDWebImageProgressiveDownload|SDWebImageRetryFailed|SDWebImageLowPriority progress:^(NSUInteger receivedSize, long long expectedSize){
        if (!activityIndicator){
            [weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
            activityIndicator.center = weakImageView.center;
            [activityIndicator startAnimating];
        }
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType){
        [activityIndicator removeFromSuperview];
        activityIndicator = nil;
    }];
    if (_communityCategory == 2 && isBusi) {//我要投票
        //绑定查看详情事件
        _gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewImageItemDetail:)];
        //使用关联函数方式传递参数－扩展属性
        objc_setAssociatedObject(_gesture, &associatedkey, param, OBJC_ASSOCIATION_RETAIN);
        imageView.userInteractionEnabled = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        [imageView addGestureRecognizer:_gesture];
    }else {//民意征集
        //绑定浏览事件
        //用于给图片绑定事件
        _gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandle:)];
        imageView.userInteractionEnabled = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        [imageView addGestureRecognizer:_gesture];
        [_imageViews addObject:imageView];
    }
}

/**复选框事件*/
-(void)checkBoxClicked:(id)sender{
    CheckButton * cb=( CheckButton *)sender;
    if(cb.enable){
        NSMutableSet *cSubResult;//可变集合
        if([_cResultDic objectForKey:_masterId]) {//存在
            cSubResult = [_cResultDic objectForKey:_masterId];
        } else {//不存在
            cSubResult = [NSMutableSet setWithCapacity:30];
        }
        if (cb.checked) {//如果选中
            [cSubResult addObject:cb.value];
        }else {
            [cSubResult removeObject:cb.value];
        }
        [_cResultDic setValue:cSubResult forKey:_masterId];
    }
}

/**单选框事件*/
-(void)radioClicked:(id)sender{
    CheckButton * cb=( CheckButton *)sender;
    if(cb.enable){
        if (cb.checked) {//如果选中
            [_rResultDic setValue:cb.value forKey:_masterId];
        }else {
            [_rResultDic removeObjectForKey:_masterId];
        }
    }
}

/**
 *我要投票－查看选项详情-文本类型
 */
- (void)viewTextItemDetail:(id)sender{
    UIButton *labelBtn=(UIButton *)sender;
    NSString *str = objc_getAssociatedObject(labelBtn, &associatedkey);
    NSDictionary *nsd =[CommonUtil stringToDic:str];
    //进入下一级页面
    ConfigableViewController *vc = [[VoteItemDetailViewController alloc]initWithNibName:@"VoteItemDetailViewController" bundle:nil];
    vc.config = [NSDictionary dictionaryWithObjectsAndKeys:nsd, @"dataItem", nil];
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 *我要投票－查看选项详情－图片类型
 */
- (void)viewImageItemDetail:(id)sender{
    UITapGestureRecognizer *gesture = (UITapGestureRecognizer*)sender;
    NSString *str =objc_getAssociatedObject(gesture, &associatedkey);
    NSDictionary *nsd =[CommonUtil stringToDic:str];
    //进入下一级页面
    ConfigableViewController *vc = [[VoteItemDetailViewController alloc]initWithNibName:@"VoteItemDetailViewController" bundle:nil];
    vc.config = [NSDictionary dictionaryWithObjectsAndKeys:nsd, @"dataItem", nil];
    [self.navigationController pushViewController:vc animated:YES];
}

//投票结果展示相关方法
//========================
/**
 *我要投票－创建显示投票结果区域
 *@param json
 */
- (void)createVoteResult:(NSDictionary *)json{
    //分割线
    UITextView* spiritLine = [[UITextView alloc] initWithFrame:CGRectMake(10, _nextY, 300, 0.5)];
    spiritLine.backgroundColor = [UIColor blackColor];
    [self.mainPanel addSubview:spiritLine];
    
    _nextY += 5.5;//与下一元素的垂直间距为10.5
    
    //文字tip
    //--------------
    NSString * labelStr = @"结果";
    UIButton *labelBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, _nextY, 250, 32)];
    [labelBtn setTitle:labelStr forState:UIControlStateNormal];
    labelBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    [labelBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    labelBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;//文字水平居左
    labelBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter ;//文字垂直居中
    //使文字距离左边框保持10个像素的距离。
    labelBtn.contentEdgeInsets = UIEdgeInsetsMake(0,0, 0, 0);
    [self.mainPanel addSubview:labelBtn];
    
    _nextY += 30;//与下一元素的垂直间距为30
    
    //投票结果显示区
    //-----------------
    int itemNum=1;
    int detailsType = -1;//0表示列表投票项，1表示图片投票项，2表示意见项
    int voteNum = -1;//投票项获取票数
    for(NSDictionary *nsd in json){
        detailsType = [CommonUtil dealNullObject:[nsd objectForKey:@"detailsType"]].intValue;
        if (detailsType == 1) {
            voteNum = [CommonUtil dealNullObject:[nsd objectForKey:@"voteNum"]].intValue;
            //投票项占比－进度条方式显示
            [self createProgressItem:itemNum iTitle:[CommonUtil dealNullObject:[nsd objectForKey:@"voteItemContext"]]
                            iVoteNum:voteNum
                         iPercentage:[CommonUtil roundUp:((float)voteNum/_voteItemSum) afterScale:2]];
            itemNum++;
        }
    }
}

/**
 *创建进度条
 *@param indexPath 条项排序号
 *@param iTitle 条项标题
 *@param iVoteNum 条项获取票数
 *@param iPercentage 百分比
 */
- (void) createProgressItem:(int)indexPath iTitle:(NSString *)iTitle iVoteNum:(int)iVoteNum iPercentage:(NSString *)iPercentage{
    //文字tip
    //--------------
    NSString * labelStr = iTitle;
    UIButton *labelBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, _nextY, 250, 32)];
    [labelBtn setTitle:labelStr forState:UIControlStateNormal];
    labelBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    [labelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    labelBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;//文字水平居左
    labelBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter ;//文字垂直居中
    //使文字距离左边框保持10个像素的距离。
    labelBtn.contentEdgeInsets = UIEdgeInsetsMake(0,0, 0, 0);
    [self.mainPanel addSubview:labelBtn];
    
    _nextY += 40;//与下一元素的垂直间距为42
    
    //进度条
    //-----------------
    NSArray *gradientColors;
    switch (indexPath) {//不同次序的进度条，显示不同的颜色值
        case 0://#0099cc
            gradientColors = [NSArray arrayWithObjects:[CommonUtil stringToColor:@"#0099cc"], nil];
            break;
        case 1://#ff8800
            gradientColors = [NSArray arrayWithObjects:[CommonUtil stringToColor:@"#ff8800"], nil];
            break;
        case 2://#669900
            gradientColors = [NSArray arrayWithObjects:[CommonUtil stringToColor:@"#669900"], nil];
            break;
        case 3://#9933cc
            gradientColors = [NSArray arrayWithObjects:[CommonUtil stringToColor:@"#9933cc"], nil];
            break;
        case 4://#cc0000
            gradientColors = [NSArray arrayWithObjects:[CommonUtil stringToColor:@"#cc0000"], nil];
            break;
        case 5://85edb9
            gradientColors = [NSArray arrayWithObjects:[CommonUtil stringToColor:@"#85edb9"], nil];
            break;
        case 6://#ee4458
            gradientColors = [NSArray arrayWithObjects:[CommonUtil stringToColor:@"#ee4458"], nil];
            break;
        case 7://#fcb74d
            gradientColors = [NSArray arrayWithObjects:[CommonUtil stringToColor:@"#fcb74d"], nil];
            break;
        case 8://#427fed
            gradientColors = [NSArray arrayWithObjects:[CommonUtil stringToColor:@"#427fed"], nil];
            break;
        case 9://#b23424
            gradientColors = [NSArray arrayWithObjects:[CommonUtil stringToColor:@"#b23424"], nil];
            break;
        default://#0099cc
            gradientColors = [NSArray arrayWithObjects:[CommonUtil stringToColor:@"#0099cc"], nil];
            break;
    }
    AMProgressView *pv = [[AMProgressView alloc] initWithFrame:CGRectMake(20, _nextY, 230, 25)
                                             andGradientColors:gradientColors
                                              andOutsideBorder:NO
                                                   andVertical:NO];
    
    // Configure
    pv.progress = [iPercentage floatValue];
    pv.emptyPartAlpha = 0.9f;
    [self.mainPanel addSubview:pv];
    //百分比-与进度条左右并排
    //-----------------
    NSString * percentageStr = [NSString stringWithFormat:@"%d(%@％)",iVoteNum,[CommonUtil roundUp:([iPercentage floatValue]*100) afterScale:2]];
    
    UIButton *percentageBtn = [[UIButton alloc] initWithFrame:CGRectMake(250, _nextY, 50, 25)];
    [percentageBtn setTitle:percentageStr forState:UIControlStateNormal];
    percentageBtn.titleLabel.font = [UIFont systemFontOfSize: 13.0];
    [percentageBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    percentageBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;//文字水平居左
    percentageBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter ;//文字垂直居中
    //使文字边框距离
    percentageBtn.contentEdgeInsets = UIEdgeInsetsMake(0,0, 0, 0);
    [self.mainPanel addSubview:percentageBtn];
    
    _nextY += 37;//与下一元素的垂直间距为37
}

//提交投票相关方法
//========================
/**
 *创建提交按钮
 *@param btnType 创建的按钮类型：post提交按钮；end结束
 */
- (UIButton*)createBtn:(NSString *)btnType{
    int height = iPhone5 ? 0 : 88 ;
    //生成底部按扭-提交
    if ([btnType isEqualToString:@"post"]) {
        UIButton *postBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,460 - height, 320, 44)];
        [postBtn setBackgroundImage:[UIImage imageNamed:@"btnImage.png"] forState:0];
        [postBtn setTitle:@"提交" forState:0];
        [postBtn addTarget:self action:@selector(postResult:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:postBtn];
        return postBtn;
    }else{//生成底部按扭－已结束
        UIButton *endBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 460 - height, 320, 44)];
        [endBtn setBackgroundImage:[UIImage imageNamed:@"black_line.jpg"] forState:0];
        [endBtn setTitle:@"已结束" forState:0];
        [endBtn addTarget:self action:@selector(endResult:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:endBtn];
        return endBtn;
    }
    _nextY+=50;
    
}

/**提交调查／投票结果*/
- (void)postResult:(id) sender{
    //判断是否均已选择
    if(![_rResultDic objectForKey:_masterId] && ![_cResultDic objectForKey:_masterId]){
        [self.view makeToast:@"请进行选择" duration:2.0 position:@"center"];
        return;
    }
    //进行提交
    [self startLoadingViewWithText:@"正在提交..."];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:SERVER_URL_SUBMIT_VOTE customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:[self toJsonParams] httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        //关闭提示加载框
        [self stopLoadingView];
        NSDictionary *json = [completedOperation responseJSON];
        NSString *tipStr = [CommonUtil dealNullObject:[json objectForKey:@"message"]];
        tipStr = [tipStr equals:@""]?@"报名成功":tipStr;
        [self.view makeToast:tipStr duration:2.0 position:@"center"];
        
        //刷新当前页
        [self refreshPageOne];
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        //关闭提示加载框
        [self stopLoadingView];
        [self.view makeToast:@"提交失败，请重新登录再操作" duration:2.0 position:@"center"];
    }];
    [currentEngine enqueueOperation:op];
}

/**格式化参数集合*/
- (NSMutableDictionary *)toJsonParams{
    NSString *voteItemIds = @"";
    //单选结果
    if ([_rResultDic count]>0) {
        for(NSString *value in _rResultDic.allValues){
            if([voteItemIds equals:@""]){
                voteItemIds = [[CommonUtil dealNullObject:value]  stringByAppendingString:@","];
            }else{
                voteItemIds = [voteItemIds stringByAppendingString: [CommonUtil dealNullObject:value]];
            }
        }
    }
    //复选结果
    if ([_cResultDic count]>0) {
        NSMutableSet *tempSet;
        for(NSString *key in _cResultDic.allKeys){
            tempSet = [_cResultDic objectForKey:key];
            if (tempSet && [tempSet count]>0) {
                for (NSString *object in tempSet) {
                    if([voteItemIds equals:@""]){
                        voteItemIds = [[CommonUtil dealNullObject:object]  stringByAppendingString:@","];
                    }else{
                        voteItemIds = [voteItemIds stringByAppendingString: [CommonUtil dealNullObject:object]];
                    }
                }
            }
        }
    }
    
    NSMutableDictionary *subParams = [NSMutableDictionary dictionary];
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    [subParams setValue:userInfo.userInfo.Id forKey:@"userID"];
    [subParams setValue:userInfo.userInfo.userName forKey:@"voteName"];
    [subParams setValue:_masterId forKey:@"voteMasterID"];
    [subParams setValue:voteItemIds forKey:@"voteItemIDs"];
    
    return subParams;
}

/**提示已结束*/
- (void)endResult:(id) sender{
    if (_communityCategory == 2) {
        //我要投票
        [self.view makeToast:@"此次投票已结束，谢谢您的参与" duration:2.0 position:@"center"];
    }else {//民意征集
        [self.view makeToast:@"此次征集已结束，谢谢您的参与" duration:2.0 position:@"center"];
    }
}

//意见提交相关方法
//========================
/**
 *创建意见填写框
 */
- (void)createOpinionZone{
    NSString *opinionStr = [CommonUtil dealNullObject:[_opinionData objectForKey:@"voteOpinion"]];
    //文字tip
    //--------------
    NSString * labelStr = @"您的意见";
    UIButton *labelBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, _nextY, 250, 32)];
    [labelBtn setTitle:labelStr forState:UIControlStateNormal];
    labelBtn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    [labelBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    labelBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;//文字水平居左
    labelBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter ;//文字垂直居中
    //使文字距离左边框保持10个像素的距离。
    labelBtn.contentEdgeInsets = UIEdgeInsetsMake(0,0, 0, 0);
    [self.mainPanel addSubview:labelBtn];
    
    _nextY += 42;//与下一元素的垂直间距为42
    
    //填写框
    //--------------
    _opinionField = [[UITextView alloc] initWithFrame:CGRectMake(10, _nextY, 300, 100)];
    _opinionField.inputAccessoryView = [self getInputAccessoryView];
    _opinionField.delegate = self;
    if([opinionStr equals:@""]){
        _opinionField.editable = YES;
    }else{
        _opinionField.editable = NO;
    }
    _opinionField.textAlignment = NSTextAlignmentLeft;//左对齐
    _opinionField.font = [UIFont systemFontOfSize: 13.0];
    _opinionField.text = opinionStr;
    
    _opinionField.layer.backgroundColor = [[UIColor clearColor] CGColor];//背景色
    //设置边框
    _opinionField.layer.borderColor = [[UIColor orangeColor]CGColor];
    _opinionField.layer.borderWidth = 1.0;
    _opinionField.layer.cornerRadius = 8.0f;
    [_opinionField.layer setMasksToBounds:YES];
    
    [self.mainPanel addSubview:_opinionField];
    
    _nextY += 110;//与下一元素的垂直间距为110
}
/**
 *创建意见提交按钮
 */
- (UIButton*)createOpinionBtn{
    int height = iPhone5 ? 0 : 88 ;
    //生成底部按扭-意见提交按钮
    UIButton *postBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,460 - height, 320, 44)];
    [postBtn setBackgroundImage:[UIImage imageNamed:@"btnImage.png"] forState:0];
    [postBtn setTitle:@"提交" forState:0];
    [postBtn addTarget:self action:@selector(postOpinionResult:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:postBtn];
    _nextY+=50;
    return postBtn;
}

/**我要投票－提交意见*/
- (void)postOpinionResult:(id) sender{
    NSString *opinionStr = [CommonUtil dealNullObject:_opinionField.text];
    //判断是否均已选择
    if([opinionStr equals:@""]){
        [self.view makeToast:@"请填写意见" duration:2.0 position:@"center"];
        return;
    }
    NSMutableDictionary *subParams = [NSMutableDictionary dictionary];
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    [subParams setValue:userInfo.userInfo.Id forKey:@"userID"];
    [subParams setValue:userInfo.userInfo.userName forKey:@"voteName"];
    [subParams setValue:_masterId forKey:@"voteMasterID"];
    [subParams setValue:[CommonUtil dealNullObject:[_opinionData objectForKey:@"id"]] forKey:@"voteItemID"];
    [subParams setValue:opinionStr forKey:@"voteOpinion"];
    //进行提交
    [self startLoadingViewWithText:@"正在提交..."];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:SERVER_URL_SUBMIT_VOTE_RESULT customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:subParams httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        //关闭提示加载框
        [self stopLoadingView];
        NSDictionary *json = [completedOperation responseJSON];
        NSString *tipStr = [CommonUtil dealNullObject:[json objectForKey:@"message"]];
        tipStr = [tipStr equals:@""]?@"报名成功":tipStr;
        [self.view makeToast:tipStr duration:2.0 position:@"center"];
        
        //刷新当前页
        [self refreshPageTwo];
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        //关闭提示加载框
        [self stopLoadingView];
        [self.view makeToast:@"提交失败，请重新登录再操作" duration:2.0 position:@"center"];
    }];
    [currentEngine enqueueOperation:op];
}
//其他方法
//========================

//提交投票成功后，刷新当前页
- (void)refreshPageOne{
    //重新加载当前页面
    NSMutableDictionary *mConfig =[NSMutableDictionary dictionaryWithDictionary:_config];
    VoteMasterEntity *item = [mConfig objectForKey:@"dataItem"];
    item.countNum = @"1";
    [mConfig setValue:item forKey:@"dataItem"];
    self.config = mConfig;
    [self.view setNeedsDisplay];
    //发送通知刷新列表
    [[NSNotificationCenter defaultCenter]postNotificationName:@"RefreshList" object:nil userInfo:@{@"key":@"社区自治",@"uid":item.Id}];
    _postBtn.hidden = YES;
    [self configView];
}

//意见提交成功后，刷新当前页
- (void)refreshPageTwo{
    //刷新当前页
    [self.view setNeedsDisplay];
    _opinionBtn.hidden = YES;
    [self configView];
}

//图片浏览事件
- (void)tapHandle:(UITapGestureRecognizer *)tap {
    XHImageViewer *imageViewer = [[XHImageViewer alloc] init];
    imageViewer.delegate = self;
    imageViewer.disableTouchDismiss = NO;
    [imageViewer showWithImageViews:_imageViews selectedView:(UIImageView *)tap.view];
}

#pragma mark - Text View Delegate
//开始输入的时候向上移动整个界面，这个输入框不会被挡住
-(void)textViewDidBeginEditing:(UITextView *)textView{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y - INPUT_VIEW_OFFSET/3;
    self.view.frame = frame;
    [UIView commitAnimations];
}

//输入结束的时候把整个界面向下移动，这个能恢复正常
-(void)textViewDidEndEditing:(UITextView *)textView{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y + INPUT_VIEW_OFFSET/3;
    self.view.frame = frame;
    [UIView commitAnimations];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end